import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/evaluation.dart';
import 'package:ichinesereader/models/evaluation/evaluationOverviewResult.dart';
import 'package:ichinesereader/pages/teacher/benchmarkOverviewContent.dart';
import 'package:ichinesereader/pages/teacher/evaluationOverviewContent.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:dropdown_search/dropdown_search.dart';
import 'package:ichinesereader/widgets/buttons/floatingActionButtonsTeacherSwitchClass.dart';
import '../../themes/appTheme.dart';

class EvaluationOverviewChartsPage extends StatefulWidget {
  @override
  _EvaluationOverviewChartsPageState createState() =>
      _EvaluationOverviewChartsPageState();
}

class _EvaluationOverviewChartsPageState
    extends State<EvaluationOverviewChartsPage> {
  final box = Hive.box('appconfig');
  final myKey = GlobalKey<DropdownSearchState<StudentList>>();
  final EvaluationController controller = Get.find();
  String classId = '';
  String _levelStandard = Constants.levelStandardTypes[0];
  List<StudentList> _selectedStudentLists = [];
  String _mode = Constants.overviewChartModes[0];

  @override
  void initState() {
    classId = box.get(CacheManagerKey['currentclass'].toString());
    Future.delayed(Duration(milliseconds: 200), (() {
      if (_mode == Constants.overviewChartModes[0]) {
        controller.fetchEvaluationOverviewData(classId);
      }
      if (_mode == Constants.overviewChartModes[1]) {
        controller.fetchBenchmarkOverviewData(classId);
      }
    }));

    super.initState();
  }

  onSelectStudent(List<StudentList> students) {
    _selectedStudentLists = students;
    controller.doRefresh();
    if (_mode == Constants.overviewChartModes[0]) {
      controller.refreshEvaluationOverviewData(classId);
    }
    if (_mode == Constants.overviewChartModes[1]) {
      controller.refreshBenchmarkOverviewData(classId);
    }
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build teacher evaluation overview charts page');

    return Scaffold(
      backgroundColor: Colors.transparent,
      floatingActionButton: FloatingActionButtonsTeacherSwitchClass(),
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        child: Column(
          children: [
            Container(
              decoration: BoxDecoration(
                color: Get.isDarkMode
                    ? Colors.black
                    : Colors.black.withOpacity(0.1),
              ),
              child: Padding(
                  padding: const EdgeInsets.only(left: 12.0),
                  child: controller.obx(
                    (data) {
                      if (controller.evaluationOverviewData.value.studentList !=
                          null) {
                        return Row(children: [
                          Expanded(
                            child: DropdownSearch<StudentList>.multiSelection(
                              itemAsString: (item) {
                                return item.userName.toString();
                              },
                              dropdownDecoratorProps: DropDownDecoratorProps(
                                dropdownSearchDecoration: InputDecoration(
                                  labelText: "Choose Student".tr,
                                  labelStyle: TextStyle(
                                      color: Get.theme.primaryColorLight),
                                ),
                              ),
                              popupProps: PopupPropsMultiSelection.menu(
                                  showSearchBox: true,
                                  itemBuilder: (ctx, item, isSelected) {
                                    return ListTile(
                                        tileColor: Get.isDarkMode
                                            ? AppTheme.colors.darkTheme4
                                            : Get.theme.primaryColorLight,
                                        selected: false,
                                        title: Text(item.userName.toString()));
                                  }),
                              key: myKey,
                              items: controller.evaluationOverviewData.value
                                  .studentList as List<StudentList>,
                              selectedItems: [],
                              onChanged: onSelectStudent,
                            ),
                          ),
                        ]);
                      } else {
                        return Text('');
                      }
                    },
                    // onLoading:
                    //     Center(child: CircularProgressIndicator()),
                  )),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 6.0),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Container(
                    width: 300,
                    // padding: EdgeInsets.only(left: 10),
                    child: FormBuilderChoiceChip(
                      decoration: InputDecoration.collapsed(
                        hintText: '',
                        border: InputBorder.none,
                      ),
                      spacing: 6.0,
                      backgroundColor:
                          Get.isDarkMode ? Get.theme.primaryColor : Colors.grey,
                      selectedColor: Get.isDarkMode
                          ? Get.theme.primaryColorDark
                          : AppTheme.colors.orangeBtn,
                      name: 'overview_chart_mode',
                      onChanged: (value) {
                        if (value == null) return;
                        _mode = value.toString();
                        if (_mode == Constants.overviewChartModes[0]) {
                          controller.fetchEvaluationOverviewData(classId);
                        }
                        if (_mode == Constants.overviewChartModes[1]) {
                          controller.fetchBenchmarkOverviewData(classId);
                        }
                      },
                      initialValue: Constants.overviewChartModes[0],
                      options: Constants.overviewChartModes
                          .map((state) => FormBuilderChipOption<String>(
                                value: state,
                                child: Text(
                                  state.toString(),
                                  style: TextStyle(
                                      fontSize: 13.0,
                                      letterSpacing: 0.8,
                                      color: Get.isDarkMode
                                          ? Colors.black
                                          : AppTheme.colors.lightOrange),
                                ),
                              ))
                          .toList(),
                    ),
                  ),
                  Container(
                      width: 180,
                      child: FormBuilderChoiceChip(
                        decoration: InputDecoration.collapsed(
                          hintText: '',
                          border: InputBorder.none,
                        ),
                        alignment: WrapAlignment.end,
                        spacing: 6.0,
                        padding: EdgeInsets.symmetric(horizontal: 18.0),
                        backgroundColor: Get.isDarkMode
                            ? Get.theme.primaryColor
                            : Colors.grey,
                        selectedColor: Get.isDarkMode
                            ? Theme.of(context).primaryColorDark
                            : Get.theme.primaryColorDark,
                        name: 'level_standard_types',
                        onChanged: (value) {
                          if (value == null) return;
                          _levelStandard = value.toString();
                          controller.doRefresh();
                          if (_mode == Constants.overviewChartModes[0]) {
                            controller.refreshEvaluationOverviewData(classId);
                          }
                          if (_mode == Constants.overviewChartModes[1]) {
                            controller.refreshBenchmarkOverviewData(classId);
                          }
                        },
                        initialValue: Constants.levelStandardTypes[0],

                        ///这里暂时去掉yct,hsk
                        options: Constants.levelStandardTypes
                            .where((element) =>
                                element != 'YCT' && element != 'HSK')
                            .map((state) => FormBuilderChipOption<String>(
                                  value: state,
                                  child: Text(
                                    state.toString(),
                                    style: TextStyle(
                                        color: Get.isDarkMode
                                            ? Colors.black
                                            : Get.theme.primaryColorLight),
                                  ),
                                ))
                            .toList(),
                      ))
                ],
              ),
            ),
            controller.obx((data) {
              if (_mode == Constants.overviewChartModes[0] &&
                  controller.forceRefresh)
                return EvaluationOverviewContent(
                    levelStandard: _levelStandard,
                    selectedStudentLists: _selectedStudentLists);
              if (_mode == Constants.overviewChartModes[1] &&
                  controller.forceRefresh)
                return BenchmarkOverviewContent(
                    levelStandard: _levelStandard,
                    selectedStudentLists: _selectedStudentLists);
              else
                return Text('');
            })
          ],
        ),
      ),
    );
  }
}
